/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.model;

import java.io.IOException;

/**
 * Date: Feb 19, 2011
 *
 * @author Michael Morozov
 */
public class Piece implements IPiece
{
    private long to;
    private String value;
    private long from;
    private ISource source;
    private boolean used = false;

    private void refreshCache(long oldFrom, long oldTo)
    {
        if (value != null)
        {

            int indexFrom = -1;
            if (oldFrom <= from)
                indexFrom = (int) (from - oldFrom);

            int indexTo = -1;
            if (oldTo >= to)
                indexTo = (int) (value.length() - oldTo + to);

            value = indexFrom >= 0 && indexTo >= 0 ? value.substring(indexFrom, indexTo) : null;
        }
    }

    public String getCachedValue() throws IOException
    {
        if (value == null)
        {
            value = source.read(from, to);
            to = from + value.length();
        }
        return value;
    }

    public IPiece resetCache()
    {
        value = null;
        return this;
    }

    public IPiece markAsUsed()
    {
        used = true;
        return this;
    }

    public boolean isUsed()
    {
        return used;
    }

    public IPiece copy()
    {
        Piece result = new Piece(source, from, to);
        result.value = value;
        return result;
    }

    public ISource getSource()
    {
        return source;
    }

    public long getFrom()
    {
        return from;
    }

    public long getLength()
    {
        return to - from;
    }

    public long getTo()
    {
        return to;
    }

    public IPiece setFrom(long from)
    {
        long oldFrom = this.from;
        this.from = from;
        refreshCache(oldFrom, to);
        return this;
    }

    public IPiece setTo(long to)
    {
        long oldTo = this.to;
        this.to = to;
        refreshCache(from, oldTo);
        return this;
    }

    public Piece(ISource source, long from, long to)
    {
        this.to = to;
        this.source = source;
        this.from = from;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();    //To change body of overridden methods use File | Settings | File Templates.
    }
}
